package com.travel.server.manager.impl.command.message;

import com.travel.common.util.CollectionUtil;
import com.travel.server.manager.dto.request.PageRequest;
import com.travel.server.manager.dto.response.message.QueryMessageMailListResponse;
import com.travel.server.manager.dto.response.message.QueryMessageMailListResponse.MailItem;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.MessageDal;
import com.travel.server.manager.impl.dal.MessageDal.MessageParam;
import com.travel.server.manager.impl.dal.PageDto;
import com.travel.server.manager.impl.enums.MessageTemplateEnum;
import com.travel.server.manager.model.MessageTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LiZhenhui
 * @Date: 2018\11\15 0015 22:18
 * @Desc:
 */
@Component
@Slf4j
public class QueryMessageMailListCommand extends AbstractCommand<PageRequest, QueryMessageMailListResponse> {

    @Autowired
    private MessageDal messageDal;

    @Override
    protected void checkInput(PageRequest request) {
        checkPageInput(request);
    }

    @Override
    public QueryMessageMailListResponse handle(PageRequest request) {
        checkInput(request);
        MessageParam messageParam = makeParam(request);
        PageDto<MessageTemplate> pageDto = messageDal.select(messageParam);

        return makeResponse(pageDto);
    }

    private QueryMessageMailListResponse makeResponse(PageDto<MessageTemplate> pageDto){
        QueryMessageMailListResponse response = new QueryMessageMailListResponse();
        List<MailItem> mailList = new ArrayList<>();
        int total = pageDto.getTotal();
        List<MessageTemplate> list = pageDto.getList();
        if(!CollectionUtil.isEmpty(list)){
            for(MessageTemplate message : list){
                MailItem item = new MailItem();
                item.setContent(message.getMessageContent());
                item.setId(message.getId());
                item.setName(message.getMessageTitle());
                item.setRemark(message.getMailRemark());
                item.setTheme(message.getMailTheme());
                item.setSender(message.getMailSender());
                mailList.add(item);
            }
        }
        response.setMessageList(mailList);
        response.setTotalNum(total);
        return response;
    }

    private MessageParam makeParam(PageRequest request){
        MessageParam param = new MessageParam();
        param.setType(MessageTemplateEnum.MAIL.getType());
        param.setLimit(request.getLimit());
        param.setOffset(request.getOffset());
        return param;
    }
}
